import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tool } from '../tools/entities/tool.entity';
import { Article } from '../articles/entities/article.entity';
import { Category } from '../categories/entities/category.entity';

/**
 * SEO 服务
 * 负责生成 sitemap.xml 和其他 SEO 相关功能
 */
@Injectable()
export class SeoService {
  constructor(
    @InjectRepository(Tool)
    private toolsRepository: Repository<Tool>,
    @InjectRepository(Article)
    private articlesRepository: Repository<Article>,
    @InjectRepository(Category)
    private categoriesRepository: Repository<Category>,
  ) {}

  /**
   * 生成 sitemap XML
   */
  async generateSitemap(baseUrl: string): Promise<string> {
    const urls: SitemapUrl[] = [];

    // 1. 添加首页
    urls.push({
      loc: baseUrl,
      lastmod: new Date().toISOString().split('T')[0],
      changefreq: 'daily',
      priority: '1.0',
    });

    // 2. 添加工具列表页
    urls.push({
      loc: `${baseUrl}/tools`,
      lastmod: new Date().toISOString().split('T')[0],
      changefreq: 'daily',
      priority: '0.9',
    });

    // 3. 添加所有工具详情页
    const tools = await this.toolsRepository.find({
      order: { updatedAt: 'DESC' },
    });

    for (const tool of tools) {
      urls.push({
        loc: `${baseUrl}/tools/${tool.slug}`,
        lastmod: tool.updatedAt.toISOString().split('T')[0],
        changefreq: 'weekly',
        priority: '0.8',
      });
    }

    // 4. 添加文章列表页
    urls.push({
      loc: `${baseUrl}/articles`,
      lastmod: new Date().toISOString().split('T')[0],
      changefreq: 'daily',
      priority: '0.8',
    });

    // 5. 添加所有文章详情页
    const articles = await this.articlesRepository.find({
      where: { status: 'published' },
      order: { updatedAt: 'DESC' },
    });

    for (const article of articles) {
      urls.push({
        loc: `${baseUrl}/articles/${article.slug}`,
        lastmod: article.updatedAt.toISOString().split('T')[0],
        changefreq: 'monthly',
        priority: '0.7',
      });
    }

    // 6. 添加分类页面
    const categories = await this.categoriesRepository.find();
    for (const category of categories) {
      urls.push({
        loc: `${baseUrl}/tools?category=${category.id}`,
        lastmod: new Date().toISOString().split('T')[0],
        changefreq: 'weekly',
        priority: '0.7',
      });
    }

    // 7. 添加其他重要页面
    const otherPages = [
      { path: '/pricing', priority: '0.8' },
      { path: '/about', priority: '0.6' },
      { path: '/contact', priority: '0.6' },
    ];

    for (const page of otherPages) {
      urls.push({
        loc: `${baseUrl}${page.path}`,
        lastmod: new Date().toISOString().split('T')[0],
        changefreq: 'monthly',
        priority: page.priority,
      });
    }

    // 生成 XML
    return this.buildSitemapXml(urls);
  }

  /**
   * 构建 sitemap XML 字符串
   */
  private buildSitemapXml(urls: SitemapUrl[]): string {
    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';

    for (const url of urls) {
      xml += '  <url>\n';
      xml += `    <loc>${this.escapeXml(url.loc)}</loc>\n`;
      xml += `    <lastmod>${url.lastmod}</lastmod>\n`;
      xml += `    <changefreq>${url.changefreq}</changefreq>\n`;
      xml += `    <priority>${url.priority}</priority>\n`;
      xml += '  </url>\n';
    }

    xml += '</urlset>';
    return xml;
  }

  /**
   * XML 转义
   */
  private escapeXml(text: string): string {
    return text
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&apos;');
  }

  /**
   * 生成 robots.txt（备用方案，主要还是用前端的静态文件）
   */
  generateRobotsTxt(baseUrl: string): string {
    return `# robots.txt for DevTools Hub
User-agent: *
Allow: /
Disallow: /admin/
Disallow: /api/
Disallow: /login
Disallow: /register
Disallow: /order/

Sitemap: ${baseUrl}/sitemap.xml
`;
  }
}

/**
 * Sitemap URL 接口
 */
interface SitemapUrl {
  loc: string;
  lastmod: string;
  changefreq: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
  priority: string;
}

